import baseUrl from "./urlConfig.js"
import util from "../util.js"

var amapFile = require('../amap-wx.js');

const request = {}

// request请求封装
request.sendRequest = function(param) {
	var _self = this,
		url = param.url,
		method = param.method,
		data = param.data,
		header = !param.header ? request.getHeader('token') : param.header;

	uni.showLoading({
		title: '加载中...'
	});

	//网络请求
	uni.request({
		url: baseUrl + url,
		method: method,
		header: header,
		data: data,
		success: (res) => {
			
			console.log("网络请求success:" + url);
			uni.hideLoading();
			uni.stopPullDownRefresh();
			
			// console.log("网络请求success:" + JSON.stringify(res));
			// console.log(res)
			if (res.data.code == 0 || res.data.code == 1) {
				typeof param.success == "function" && param.success(res);
			} else {
				if (res.data.code == 1001) {
					request.login(function(res) {
						if (res) {
							let accessToken = uni.getStorageSync('accessToken')
							var newParam = param
							newParam.header.Authorization = 'bearer ' + accessToken
							_self.sendRequest(newParam)
						} else {
							setTimeout(function() {
								uni.showToast({
									title: '登录令牌失效,请退出小程序后重新进入',
									icon: 'none'
								})
							}, 200)
						}
					})
				} else {
					setTimeout(function() {
						uni.showToast({
							title: res.data.msg,
							icon: 'none',
						})
					}, 200)
				}
			}
		},
		fail: (e) => {
			console.log("网络请求fail:" + url);
			console.log(e)
			uni.hideLoading();
			uni.stopPullDownRefresh();
			typeof param.fail == "function" && param.fail(e);
		},
		complete: () => {
			
			typeof param.complete == "function" && param.complete();
			return;
		}
	});
}

request.getHeader = function(type, submitType) {
	var defaultHeader = {
		"Content-Type": "application/x-www-form-urlencoded"
	}

	// 根据type,设置header的值
	if (type == 'void') {

	}
	if (type == 'basic') {
		defaultHeader["Authorization"] = "Basic YXBwOmFwcA=="
	}
	if (type == 'token') {
		let accessToken = uni.getStorageSync('accessToken')
		defaultHeader["Authorization"] = 'bearer ' + accessToken
	}

	if (submitType == 'json') {
		defaultHeader["Content-Type"] = "application/json;charset=UTF-8"
	}

	// 如果已登录,则userInfo已缓存,则设置header的app_user_id属性
	let userInfo = uni.getStorageSync('userInfo')
	if (userInfo) {
		// console.log('userInfo = '+JSON.stringify(userInfo))
		defaultHeader["app_user_id"] = userInfo.id
	}

	// console.log('requestHeader = ' + JSON.stringify(defaultHeader))

	return defaultHeader
}

request.reg = function(msg) {
	uni.login({
		provider: "weixin",
		scopes: "auth_user",
		success: function(res) {
			console.log('code' + res.code)

			console.log("获取微信授权信息")
			var codeRes = res
			// 获取用户信息
			uni.getSetting({
				success: res => {
					console.log("成功" + JSON.stringify(res))
					if (res.authSetting['scope.userInfo']) {
						// 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
						uni.getUserInfo({
							success: res => {
								console.log(res.signature)
								console.log(res.rawData)
								console.log(res.encryptedData)
								console.log(res.iv)

								var userRes = res
								// 将code和验证信息发送到后台,获取后台userInfo
								uni.request({
									url: baseUrl + 'app/wx/user/' + uni.getStorageSync('appId') + '/reg',
									method: 'GET',
									header: request.getHeader(),
									data: {
										code: codeRes.code,
										signature: userRes.signature,
										rawData: userRes.rawData,
										encryptedData: userRes.encryptedData,
										iv: userRes.iv,
										pullUserId: uni.getStorageSync('pullUserId')?uni.getStorageSync('pullUserId'):'0'
									},
									success: (requestRes) => {
										if (requestRes.data.code == 0) {
											console.log("注册成功" + JSON.stringify(requestRes))
											console.log("用户信息:" + JSON.stringify(requestRes))
											uni.setStorageSync('userInfo', requestRes.data.data)
											uni.setStorageSync('accessToken', requestRes.data.data.accessToken)
											uni.$emit('loginSuccess', {
												msg: '登录'
											})
											if (msg == 'getPhoneNumber') {
												if (requestRes.data.data.phone) {
													uni.$emit('getPhoneNumberSuccess', {
														msg: '绑定手机号成功'
													})
												}else{
													console.log("去授权手机号")
													uni.navigateTo({
														url: '../../pages/login/login?msg=' + msg + '&type=1',
														animationType: 'pop-in',
														animationDuration: 200
													})
												}
											}
										} else {
											console.log("注册失败" + JSON.stringify(requestRes))
											uni.removeStorageSync('userInfo')
											uni.showToast({
												title: requestRes.data.msg,
												icon: 'none'
											})
										}
									}
								})
							},
							fail(res) {
								console.log(res)
							}
						})
					} else {
						console.log("去授权")
						uni.navigateTo({
							url: '../../pages/login/login?msg=' + msg,
							animationType: 'pop-in',
							animationDuration: 200
						})
					}
				},
				fail() {
					console.log("失败")
				}
			})
		},
		fail: function() {
			console.log("获取code失败")
		},
	})
}

request.getPhoneNumber = function(){
	console.log("去授权手机号")
	uni.navigateTo({
		url: '../../pages/login/login?type=1',
		animationType: 'pop-in',
		animationDuration: 200
	})
}

request.login = function(callback) {
	uni.showLoading({
		title: '获取登录信息...'
	})
	uni.login({
		provider: "weixin",
		scopes: "auth_user",
		success: function(res) {
			console.log('code = ' + res.code)
			// 发送 res.code 到后台换取 openId, sessionKey, unionId
			uni.request({
				url: baseUrl + 'app/wx/user/' + uni.getStorageSync('appId') + '/login?code=' + res.code,
				method: 'GET',
				header: request.getHeader(),
				data: {},
				success: (res) => {
					console.log(res)
					if (res.data.code == 0) {
						console.log("登录成功")
						console.log("用户信息:" + JSON.stringify(res))
						uni.setStorageSync('userInfo', res.data.data)
						uni.$emit('loginSuccess', {
							msg: '登录成功'
						})
						
						uni.setStorageSync('accessToken', res.data.data.accessToken)
						if (callback) {
							callback(true)
						}
						
					} else {
						console.log("登录失败" + JSON.stringify(res))
						uni.removeStorageSync('userInfo')
						uni.$emit('loginFailure', {
							msg: '登录失败'
						})
						if (callback) {
							callback(false)
						}
					}
				},
				fail() {
					console.log("登录失败" + JSON.stringify(res))
					if (callback) {
						callback(false)
					}
				},
				complete() {
					uni.hideLoading()
				}
			})
		},
		fail: function() {
			console.log("获取code失败")
			uni.hideLoading()
			if (callback) {
				callback(false)
			}
		},
	})
}

request.getUserInfoById = function(uid) {
	console.log('uid = ' + uid)
	var that = this
	uni.request({
		url: baseUrl + 'app/appUser/info/' + uid,
		method: 'GET',
		header: request.getHeader('token'),
		success: res => {
			if (res.data.code == 0) {
				uni.setStorageSync('userInfo', res.data.data)
				uni.$emit('userInfoRefresh')
			} else {
				console.log("获取用户信息失败" + JSON.stringify(res))
				if (res.data.code == 1001) {
					request.login(function(res) {
						if (res) {
							request.getUserInfoById(uid)
						} else {
							uni.showToast({
								title: '登录令牌失效,请退出小程序后重新进入',
								icon: 'none'
							})
						}
					})
				} else {
					uni.showToast({
						title: res.data.msg
					});
				}
			}
		},
		fail: () => {},
		complete: () => {
			console.log("网络请求complete" + 'app/appUser/info/');
			uni.stopPullDownRefresh()
		}
	});
}

// 获取地址信息
request.getLocation = function() {
	var that = this
	console.log('请求位置信息1')
	uni.authorize({
		scope: 'scope.userLocation',
		success() {
			console.log('请求位置信息2')
			// 获取地址信息
			uni.getLocation({
				type: 'gcj02',
				geocode: true,
				success: function(e) {
					console.log('请求位置信息3' + JSON.stringify(e))
	
					var myAmapFun = new amapFile.AMapWX({
						key: 'e0999caa74772c6a7c537d77ba9955b8'
					})
					myAmapFun.getRegeo({
						success: function(res) {
							// console.log('地址反编码' + JSON.stringify(res))
							uni.setStorageSync('userLocation', res[0])
							uni.$emit('getLocationSuccess')
						},
						fail: function(info) {
							//失败回调
							console.log(info)
							uni.$emit('getLocationFailure')
						}
					})
				},
				fail() {
					uni.$emit('getLocationFailure')
				}
			})
		},
		fail(err) {
			console.log('请求位置信息fail' + JSON.stringify(err))
			uni.$emit('getLocationFailure')
		}
	})
}

export default request
